package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"time"
)

// bussiners update struct
type alluserupdate struct {
	Oldusername string `json:"oldusername"`
	Username    string `json:"username"`
	Phonenumber string `json:"phonenumber"`
	Email       string `json:"email"`
	Password    string `json:"password"`
}

// businessshop register struct
type alluserregisiter struct {
	ShopName            string `json:"shopName"`
	ProductCategories   string `json:"productCategories"`
	IdNumber            string `json:"idNumber"`
	ShopDescription     string `json:"shopDescription"`
	RegistrationAddress string `json:"registrationAddress"`
	RegistrationCapital string `json:"registrationCapital"`
	RegistrationDate    string `json:"registrationDate"`
	ShopOwner           string `json:"shopOwner"`
	ShopApprovalStatus  string `json:"shopApprovalstatus"`
}

// 商户更新个人信息
func businessupdateHandler(w http.ResponseWriter, r *http.Request) {
	method := r.Method
	if method == "PUT" {
		var updateinfo alluserupdate
		//处理修改用户信息的请求
		err := json.NewDecoder(r.Body).Decode(&updateinfo)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		//fmt.Println(updateinfo)

		//更新数据库
		_, err = db.Exec(context.Background(), "UPDATE shopping.p_business SET username=$1,phonenumber=$2,email=$3,password=$4 WHERE username=$5", updateinfo.Username, updateinfo.Phonenumber, updateinfo.Email, updateinfo.Password, updateinfo.Oldusername)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		//fmt.Println("更新成功")
		rows, err := db.Query(context.Background(), "SELECT * FROM shopping.p_business WHERE username=$1", updateinfo.Username)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		defer rows.Close()
		var newUserinfo User
		for rows.Next() {
			rows.Scan(&newUserinfo.UserType, &newUserinfo.Username, &newUserinfo.Phonenumber, &newUserinfo.Idnumber, &newUserinfo.Email, &newUserinfo.Password)
		}
		//fmt.Println(newUserinfo)

		//将更新后的用户信息返回给前端
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(newUserinfo)
	}
}

// 商户注册商店
func businessregisterHandler(w http.ResponseWriter, r *http.Request) {

	// 设置CORS headers
	w.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080") // 指定允许的源
	w.Header().Set("Access-Control-Allow-Methods", "POST")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
	w.Header().Set("Access-Control-Allow-Credentials", "true")

	method := r.Method
	if method == "POST" {
		registerinfo := alluserregisiter{
			ShopName:            r.FormValue("shopName"),
			ProductCategories:   r.FormValue("productCategories"),
			IdNumber:            r.FormValue("idNumber"),
			ShopDescription:     r.FormValue("shopDescription"),
			RegistrationAddress: r.FormValue("registrationAddress"),
			RegistrationCapital: r.FormValue("registrationCapital"),
			RegistrationDate:    r.FormValue("registrationDate"),
			ShopOwner:           r.FormValue("shopOwner"),
			ShopApprovalStatus:  r.FormValue("shopApprovalStatus"),
		}
		floatVal, err := strconv.ParseFloat(registerinfo.RegistrationCapital, 64)
		if err != nil {
			fmt.Println("Error converting string to float64:", err)
			return
		}

		file, handler, err := r.FormFile("shopImage")
		if err != nil {
			http.Error(w, "读取文件失败", http.StatusBadRequest)
			return
		}
		defer file.Close()
		fileBytes, err := io.ReadAll(file)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		filename := handler.Filename
		// fmt.Println("文件名:", filename)

		_, err = db.Exec(context.Background(), "INSERT INTO shopping.p_shopinfo(shopname,category,idnumber,introduce,address,money,createtime,state,owner,image,imagename) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)", registerinfo.ShopName, registerinfo.ProductCategories, registerinfo.IdNumber, registerinfo.ShopDescription, registerinfo.RegistrationAddress, floatVal, registerinfo.RegistrationDate, registerinfo.ShopApprovalStatus, registerinfo.ShopOwner, fileBytes, filename)
		if err != nil {
			fmt.Println("Error inserting user:", err)
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		// 返回成功响应
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode("注册成功")
	}
}

// 商户管理商店
func shopgetHandler(w http.ResponseWriter, r *http.Request) {
	method := r.Method
	if method == "POST" {
		//这里接收到的其实是用户名，而不是商店名，前端传过来的json也是叫shopname，已经做好调整不用修改
		var shopname struct {
			Name string `json:"shopname"`
		}
		err := json.NewDecoder(r.Body).Decode(&shopname)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		var shops []Returnshopinfo
		rows, err := db.Query(context.Background(), "SELECT shopname,category,idnumber,introduce,address,money,createtime,state,owner,imagename FROM shopping.p_shopinfo WHERE  owner= $1 and state = 'pass'", shopname.Name)
		if err != nil {
			fmt.Println("Error querying user:", err)
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}
		defer rows.Close()
		for rows.Next() {
			var tempdate time.Time
			var shopinfo Returnshopinfo
			err := rows.Scan(&shopinfo.ShopName, &shopinfo.Category, &shopinfo.Idnumber, &shopinfo.Introduce, &shopinfo.Address, &shopinfo.Money, &tempdate, &shopinfo.State, &shopinfo.Owner, &shopinfo.Imagename)
			if err != nil {
				fmt.Println("Error scanning row:", err)
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
			shopinfo.Createtime = tempdate.Format("2006-01-02")
			//fmt.Println(shopinfo)
			shops = append(shops, shopinfo)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Error iterating rows:", err)
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(shops) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d users\n", len(shops))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(shops)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

	} else if method == "DELETE" {
		//这里接收到的其实是用户名，而不是商店名，前端传过来的json也是叫shopname，已经做好调整不用修改
		var shop struct {
			Shopname string `json:"shopname"`
		}
		err := json.NewDecoder(r.Body).Decode(&shop)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		//将审批结果删除
		_, err = db.Exec(context.Background(), "DELETE FROM shopping.p_shopinfo WHERE owner=$1", shop.Shopname)
		if err != nil {
			fmt.Println("Delete error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		//返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "Shop deleted successfully")

	}

}

// 商户获取商品信息
func goodinfogetHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		var shopname struct {
			Name string `json:"shopname"`
		}
		err := json.NewDecoder(r.Body).Decode(&shopname)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		var goods []Good
		rows, err := db.Query(context.Background(), "SELECT *FROM shopping.p_goods WHERE shopname = $1", shopname.Name)
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {

			var good Good
			err := rows.Scan(&good.Shopname, &good.Goodname, &good.Goodprice, &good.Goodcount)
			if err != nil {
				fmt.Println(err)
			}
			// fmt.Println(good)
			goods = append(goods, good)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(goods) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d goods\n", len(goods))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(goods)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

}

// 商户管理商品
func goodmgrHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	//增加商品
	case "POST":
		var good Good
		err := json.NewDecoder(r.Body).Decode(&good)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		//fmt.Println(good)

		var id Good
		//查询商品是否已经存在
		err = db.QueryRow(context.Background(), "SELECT * FROM shopping.p_goods WHERE shopname=$1 and goodname=$2", good.Shopname, good.Goodname).Scan(&id.Shopname, &id.Goodname, &id.Goodprice, &id.Goodcount)
		if err != nil {
			fmt.Println(err)
		}
		if len(id.Shopname) != 0 {
			// 商品已存在
			_, err = db.Exec(context.Background(), "UPDATE shopping.p_goods SET goodcount=goodcount+$1,goodprice=$2 WHERE shopname=$3 and goodname=$4", good.Goodcount, good.Goodprice, good.Shopname, good.Goodname)
		} else {
			_, err = db.Exec(context.Background(), "INSERT INTO shopping.p_goods (shopname, goodname, goodprice, goodcount) VALUES ($1, $2, $3, $4)", good.Shopname, good.Goodname, good.Goodprice, good.Goodcount)
		}

		if err != nil {
			fmt.Println("Insert error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "Good added successfully")

	//修改商品
	case "PUT":
		var good Good
		err := json.NewDecoder(r.Body).Decode(&good)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
		//更新数据库的商品
		_, err = db.Exec(context.Background(), "UPDATE shopping.p_goods SET shopname=$1, goodname=$2, goodprice=$3, goodcount=$4 WHERE  shopname=$5 and goodname=$6", good.Shopname, good.Goodname, good.Goodprice, good.Goodcount, good.Shopname, good.Goodname)
		if err != nil {
			fmt.Println("Update error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "Good updated successfully")

	//删除商品
	case "DELETE":
		var good Good
		err := json.NewDecoder(r.Body).Decode(&good)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
		//fmt.Println(good)
		//删除数据库的商品
		_, err = db.Exec(context.Background(), "DELETE FROM shopping.p_goods WHERE shopname=$1 and goodname=$2", good.Shopname, good.Goodname)
		if err != nil {
			fmt.Println("Delete error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// 返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "Good deleted successfully")
	}
}

// 商店获取它的流水
func bspurchaseinfogetHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {

		var shopname struct {
			Name string `json:"shopname"`
		}
		err := json.NewDecoder(r.Body).Decode(&shopname)
		if err != nil {

			w.WriteHeader(http.StatusBadRequest)
			return
		}
		// fmt.Println(shopname.Name)
		var purchaseinfos []Purchaseinfo
		rows, err := db.Query(context.Background(), "SELECT *FROM shopping.p_purchase WHERE shopname=$1", shopname.Name)
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {

			var purchaseinfo Purchaseinfo
			err := rows.Scan(&purchaseinfo.Username, &purchaseinfo.Shopname, &purchaseinfo.Goodname, &purchaseinfo.Goodcount, &purchaseinfo.Goodprice, &purchaseinfo.Cost)
			if err != nil {
				fmt.Println(err)
			}
			// fmt.Println("99999999999999999999999999")
			// fmt.Println(purchaseinfo)
			purchaseinfos = append(purchaseinfos, purchaseinfo)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(purchaseinfos) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d purchases\n", len(purchaseinfos))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(purchaseinfos)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}

// 商户获取评论信息
func bsgetcommentHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		var shopname1 struct {
			Name string `json:"shopname"`
		}
		//fmt.Println("shopname1.Name" + shopname1.Name)
		err := json.NewDecoder(r.Body).Decode(&shopname1)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		var comments []Comment
		// 查询数据库
		rows, err := db.Query(context.Background(), "SELECT *FROM shopping.p_comment where shopname=$1", shopname1.Name)
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {
			var tempdate time.Time
			var comment Comment
			err := rows.Scan(&comment.Username, &comment.Shopname, &comment.Goodname, &comment.Text, &tempdate)
			if err != nil {
				fmt.Println(err)
			}
			comment.Time = tempdate.Format("2006-01-02 15:04:05")
			// fmt.Println(comment.Time)
			// fmt.Println(tempdate)
			comments = append(comments, comment)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(comments) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d comments\n", len(comments))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(comments)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}
